// dama_client

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#include "dama_data.h"
#include "dama_interface.h"

#define SERVER_PORT 1234

int createSocket(char *address, int port);
void createBoard(player_t *m);
int recvControlMessage(int sock);
void recvMoveProposal(int sock, move_message_t *proposal);
void updateMatch(player_t *m, move_message_t *proposal);
void sendProposal(int sock, move_message_t *message);
void playRound(player_t *m, move_message_t *proposal);
void playMatch(player_t *m);


int main()
{
	int sock;
	
	
	// connect();
	sock = createSocket("127.0.0.1", SERVER_PORT);
	
	// Prepare ncurses interface
	
	setup_curses();
	
	player_t * m = malloc(sizeof(player_t));
	
	m->fserver = sock;
	createBoard(m);
	// printf("%c", m->board[1][0]);
	// printWhiteBoard(m->board);
	
	playMatch(m);	

	endwin();
	
	return 0;
}

// Routine di impostazione della connessione.
int createSocket(char *address, int port)
{
	int sock_fd = 0;
    struct sockaddr_in addr;
    
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons((unsigned short)port);
    
    // Converto la stringa dell'indirizzo
    if ( !inet_pton(AF_INET, address, &addr.sin_addr) ) {
        perror(strerror(errno));
        exit(1);
    }
	
	// Apro il socket
	if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror(strerror(errno));
        exit(1);
    }
    
    // Connetto al server
    if (connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror(strerror(errno));
        exit(1);
    }
	
  	return sock_fd;
}

// Creo la versione locale della tavola di gioco
void createBoard(player_t *m)
{	
	int q;
	for(int j=0; j<=2; j++){
		for(int i=0; i<8; i++)
		{
			q=i+j;
			if(even(q) == 1)
			{
				m->board[j][i]='w';
			}else{
				m->board[j][i]='e';
			}
		}
	}
	
	for(int j=3; j<=4; j++){
		for(int i=0; i<8; i++)
		{
			m->board[j][i]='e';
		}
	}
	
	for(int j=5; j<=7; j++){
		for(int i=0; i<8; i++)
		{
			q=i+j;
			if(even(q) == 1)
			{
				m->board[j][i]='b';
			}else{
				m->board[j][i]='e';
			}
		}
	}
}

int recvControlMessage(int sock)
{
	int code;
	recv(sock, &code, 4, 0);
	printf("%i\n", code);
	return code;
}

void recvMoveProposal(int sock, move_message_t *proposal)
{
	recv(sock, proposal, sizeof(move_message_t), 0);
}

void updateMatch(player_t *m, move_message_t *proposal)
{
	// TODO: aggiorno la board del client
	
	int startX = proposal->startX;
	int startY = proposal->startY;
	int endX = proposal->endX;
	int endY = proposal->endY;
	char moving = proposal->playerMoving;
	int eatX, eatY;
	
	printf("Aggiorno la board..\n");
	// Aggiorno la board
	// Svuoto casella di partenza
	m->board[proposal->startX][proposal->startY] = 'e';
	
	// Svuoto casella "mangiata" e aggiorno contatori e flag vittoria
	if(proposal->eat > 0)
	{
		eatX = startX + (endX - startX)/2;
		eatY = startY + (endY - startY)/2;
		m->board[eatX][eatY] = 'e';
		if(moving == 'w' || moving == 'W')
		{
			m->board[endX][endY] = moving;
		}else if(moving == 'b' || moving == 'B')
		{
			m->board[endX][endY] = moving;
		}
		printf("Svuoto casella mangiata\n");
	}
	// Modifico la casella di arrivo della mossa, controllo se potenziare a dama
	switch(proposal->endX)
	{
		case 7:
			if(moving == 'w')
			{
				m->board[endX][endY] = 'W';
			}else m->board[endX][endY] = moving;
			break;
		case 0:
			if(moving == 'b')
			{
				m->board[endX][endY] = 'B';
			}else m->board[endX][endY] = moving;
			break;
		default:
			m->board[endX][endY] = moving;
			break;
	}
	refresh();
	(m->player == 'w')? printWhiteBoard(m->board):
				printBlackBoard(m->board);
}

void sendProposal(int sock, move_message_t *message)
{
	if(send(sock, message, sizeof(move_message_t), 0) == -1)
	{
		printf("I've got a problem sending a move message to client\n");
	}
}

void playRound(player_t *m, move_message_t *proposal)
{
	int result = 0;
	
	while(result != 3)
	{
		// TODO: sequenza del turno------------------------------------------
		takeMove(proposal, m);
		proposal->playerMoving = m->player;
		proposal->flag = 0;
	
		sendProposal(m->fserver, proposal);
	
		result = recvControlMessage(m->fserver);
	
		switch(result)
		{
			case 0: singleWindowMessage("Mossa valida. Muovi ancora tu.");
					sleep(1);
					updateMatch(m, proposal);
					break;
			case 1: singleWindowMessage("Mossa non consentita");
					sleep(1);
					break;
			case 2: singleWindowMessage("Obbligatorio mangiare");
					sleep(1);
					break;
			case 3: singleWindowMessage("Mossa valida. Cambio turno.");
					sleep(1);
					updateMatch(m, proposal);
					break;
			case 5: singleWindowMessage("Il bianco ha vinto!");
					sleep(1);
					break;
			case 6: singleWindowMessage ("Il nero ha vinto!");
					sleep(1);
					break;
			default: singleWindowMessage("Qualcosa è andato male..");
					sleep(1);
					break;
		}
		(m->player == 'w')? printWhiteBoard(m->board):
				printBlackBoard(m->board);
		
		if(result == 5 || result == 6)
		{
			singleWindowMessage("Chiudo il client di gioco..");
			sleep(1);
			exit(0);
		}
	}
}

void playMatch(player_t *m)
{
	move_message_t *proposal = malloc(sizeof(move_message_t));
	int ctrlmsg = 0, active;
	
	// TODO: inserire sequenza partita
	ctrlmsg = recvControlMessage(m->fserver);

	if(ctrlmsg == 3)
	{
		m->player = 'w';
	}else if(ctrlmsg == 4)
	{
		m->player = 'b';
	}
	
	while(ctrlmsg < 5)
	{
		active = recvControlMessage(m->fserver);
	
		if(active == 0)
		{
			m->moving = m->player;
			playRound(m, proposal);
		} else if(active == 3) {
			(m->player == 'b')? (m->moving = 'w') : (m->moving = 'b');
			recvMoveProposal(m->fserver, proposal);
			updateMatch(m, proposal);
			/*
			if(recvControlMessage(m->fserver) == 5)
			{
				singleWindowMessage("Hanno vinto i bianchi!");
				sleep(1);
				exit(0);
			}else if(recvControlMessage(m->fserver) == 6)
			{
				singleWindowMessage("Hanno vinto i neri!");
				sleep(1);
				exit(0);
			}
			*/
		}
	}
}
